<?php

namespace cm\util;

class Webim
{
    public $config;

    function __construct($config)
    {
        $this->config = $config;
    }

    public function conn($data)
    {
        $time = time();
        if (!isset($data['time']))
            $data['time'] = $time;
        $token = $this->jia(json_encode($data));
        $url = $this->getWsLink();
        $url .= "?time={$time}&token={$token}";

        return $url;
    }

    private function getWsLink()
    {
        $conf = $this->config;
        $ip = $conf['ip'];
        $port = $conf['port'];
        $url = "ws://{$ip}:{$port}";
        return $url;
    }

    private function jia($str)
    {
        $str = base64_encode($str);
        $len = strlen($str);

        $result = "";
        for ($i = 0; $i < $len; $i++) {
            $result .= chr(ord($str[$i]) ^ 2);
        }
        return urlencode($result);
    }
}
